/** @format */
import { resultsModel } from '../../sdk'
import { CODE_TYPES } from '../../constants'
import { logFn } from '../../utils'

/**
 *  检查接口参数
 *
 *  @checkParams(['activityId', 'itemId?'])
 *
 *  itemId?  问号结尾为可选参数 不做校验
 *
 * @export
 * @param {string[]} params 参数列表
 * @return {*}
 */
export default function checkParams(params: string[]): IFunction {
  return function (target: Object, name: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value

    descriptor.value = function (...args: any[]) {
      const [context, otherArgs = {}, services = [], preCheckData = {}] = args
      const dataKeys = Object.keys(context.data)
      const requiredParams = params.filter(v => !v.endsWith('?'))
      for (let i = 0; i < requiredParams.length; i++) {
        const param = requiredParams[i]
        if (!dataKeys.includes(param) || context.data?.[param] === '') {
          logFn(context)
          return resultsModel.error(CODE_TYPES.PARAMS_ERROR, `缺少${param}参数`)
        }
      }
      return method.apply(target, [context, { ...otherArgs }, services, preCheckData])
    }
  }
}
